import React, { Component } from 'react';

export default class RichText extends Component {
  state = {
    start: 0,
    end: 0,
    currentSelection: {},
  };
  componentDidMount = () => {
    document.addEventListener('selectionchange', this.selectionchange);
    window.addEventListener('mousedown', this.mousedown);
  };
  // 鼠标按下
  mousedown = (e) => {
    // console.log()
    // const s = window.getSelection();
    if (this.state.currentSelection.rangeCount > 1) {
      e.preventDefault();
    }
  };
  // 选择改变
  selectionchange = (e) => {
    const s = window.getSelection();
    console.log(s);
    const range = s.getRangeAt(0);

    this.setState({ currentSelection: range });
    const ele = s.focusNode.parentElement;
    console.log(ele, ele.selectionStart);
    // if (s.rangeCount > 1) {
    //   e;
    // }
    // // const a = <a>qqdw qw qdw qw qwd qw </a>;
    // console.log(range);
    // range.selectNode(document.getElementById('a').text);
    // range.deleteContents();
    // range = document.createRange();
    // let newNode = document.createElement('p');
    // newNode.appendChild(document.createTextNode('New Node Inserted Here'));
    // range.selectNode(document.getElementById('a'));
    // range.insertNode(newNode);

    // window.getSelection().removeAllRanges();
  };

  // 加粗
  bold = () => {
    const s = window.getSelection();
    let str = s.toString();
    let t = '';
    for (let i = 0; i < str.length; i++) {
      console.log(str.charCodeAt(i));
      if (str[i] === '\n') {
        t += '<br />';
      } else {
        t += str[i];
      }
    }
    s.deleteFromDocument();
    const ele = s.focusNode.parentElement;
    setTimeout(() => {
      let sel, range;
      if (window.getSelection) {
        // IE9 and non-IE
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
          range = sel.getRangeAt(0);
          range.deleteContents();
          // Range.createContextualFragment() would be useful here but is
          // non-standard and not supported in all browsers (IE9, for one)
          let el = document.createElement('div');
          el.innerHTML = `<span style='font-weight: bold'>${t}</span>`;
          let frag = document.createDocumentFragment(),
            node,
            lastNode;
          while ((node = el.firstChild)) {
            lastNode = frag.appendChild(node);
          }
          range.insertNode(frag);
          // Preserve the selection
          if (lastNode) {
            range = range.cloneRange();
            range.setStartAfter(lastNode);
            range.collapse(true);
            sel.removeAllRanges();
            sel.addRange(range);
          }
        }
      } else if (document.selection && document.selection.type !== 'Control') {
        // IE < 9
        document.selection.createRange().pasteHTML(t);
      }
    }, 0);
  };

  render() {
    return (
      <div>
        <div>
          <span
            onMouseDown={(e) => {
              e.preventDefault();
            }}
            onClick={this.bold}
          >
            加粗
          </span>
          <a id="a">qqdw qw qdw qw qwd qw </a>;
        </div>
        <div
          id="edit"
          contentEditable
          style={{ width: '500px', height: '500px', border: '1px solid #999', marginTop: 20 }}
        ></div>
        <div id="a1" style={{ color: 'red', width: '5px' }}></div>
        <div id="a2" style={{ width: '5px', color: 'red' }}></div>
      </div>
    );
  }
}
